package net.lcheng.sellerCenter.controller;

import com.alibaba.fastjson.JSON;
import net.lcheng.commons.utils.PageList;
import net.lcheng.model.*;
import net.lcheng.utils.Oorder2OrderModel;
import net.lcheng.utils.OorderRefund2OrderRefundModel;
import net.lcheng.sellerCenter.utils.PhoneNumUtil;
import net.lcheng.sellerCenter.vo.RefundAddressModel;
import net.lcheng.service.TradeManageService;
import net.lcheng.service.UserService;
import net.lcheng.service.WxShopService;
import net.lcheng.vo.OrderConditionsSelectModel;
import net.lcheng.vo.OrderModel;
import net.lcheng.vo.OrderRefundModel;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by LV on 2016/7/4.
 */
@Controller
public class TradeManageController {

    @Autowired
    private UserService userService;
    @Autowired
    private WxShopService wxShopService;
    @Autowired
    private TradeManageService tradeManageService;

    private static final int PAGE_SIZE=2;

    /**
     * 获取所有订单
     * @param model model
     * @param pageIndex startPage
     * @return
     */
    @RequestMapping(value = "/order/getAllOrders",method = RequestMethod.GET)
    public String getAllOrders(Model model, @RequestParam(value = "page" ,defaultValue = "1") int pageIndex){
        Subject currentUser= SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()) {
            String userPhoneNum=currentUser.getSession().getAttribute("UserPhoneNum").toString();
            //获取用户信息
            User user=userService.getUserByPhone(userPhoneNum);
            if(user!=null){
                //查询该卖家用户的对应的商铺id
                WxShop shop=wxShopService.getShopInforByUserId(user.getUserId());
                if (shop!=null){
                    //获取shopId
                    int shopId=shop.getShopId();
                    //获取订单列表
                    PageList<OOrder> pageList=tradeManageService.getAllOrdersByShopId(shopId,PAGE_SIZE,pageIndex);

                    //将pageList.list转换成成List<OrderModel>,为了解析orderProduct的json串
                    List<OrderModel> orderModelList=Oorder2OrderModel.getOorder2OrderModel(pageList.list);
                    //Model填充
                    model.addAttribute("orderList", orderModelList);//产品列表
                    model.addAttribute("pageIndex", pageList.pageIndex);//当前页
                    model.addAttribute("totalPage", pageList.totalPage);//总页数
                    model.addAttribute("totalCount", pageList.totalCount);//总记录数
                }
                return "/orders/orders_all_orders";
            }
            //发生错误
            return "redirect:/error";
        }
        //如果没有授权就重定向会登录页面
        return "redirect:/login";
    }


    /**
     * 根据不同的订单的状态获取订单列表

     */
    @RequestMapping(value = "/order/getAllOrdersByStatus",method = RequestMethod.GET)
    public String getAllOrdersByStatus(Model model, @RequestParam(value = "status") int orderStatus,
                                       @RequestParam(value = "page" ,defaultValue = "1") int page){
        Subject currentUser= SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()) {
            String userPhoneNum=currentUser.getSession().getAttribute("UserPhoneNum").toString();
            //获取用户信息
            User user=userService.getUserByPhone(userPhoneNum);
            if(user!=null){
                //查询该卖家用户的对应的商铺id
                WxShop shop=wxShopService.getShopInforByUserId(user.getUserId());
                if (shop!=null){
                    //获取shopId
                    int shopId=shop.getShopId();
                    //获取订单列表
                    PageList<OOrder> pageList=tradeManageService.getAllOrdersByShopIdAndOrderStatus(shopId,orderStatus,PAGE_SIZE,page);

                    //将pageList.list转换成成List<OrderModel>,为了解析orderProduct的json串
                    List<OrderModel> orderModelList=Oorder2OrderModel.getOorder2OrderModel(pageList.list);
                    //填充Model
                    model.addAttribute("orderList",orderModelList);//产品列表
                    model.addAttribute("pageIndex", pageList.pageIndex);//当前页
                    model.addAttribute("totalPage", pageList.totalPage);//总页数
                    model.addAttribute("totalCount", pageList.totalCount);//总记录数

                    switch (orderStatus){
                        case -1:return "/orders/orders_close_orders";//已关闭的订单
                        case 0:return "/orders/orders_payment_no_orders";//待支付列表
                        case 1:return "/orders/orders_payment_yes_orders";//已支付列表
                        case 2:return "/orders/orders_goods_send_orders";//已发货列表
                        case 3:return "/orders/orders_goods_get_orders";//已收货列表
                    }
                }
            }
            //发生错误
            return "redirect:/error";

        }
        //如果没有授权就重定向会登录页面
        return "redirect:/login";
    }



    /**
     * 订单详情
     * @param model
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/order/ordersInfor",method = RequestMethod.GET)
    public String ordersInfor(Model model,@RequestParam("oid") String orderId){
        Subject currentUser= SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()) {
            if (orderId!=null) {
                OOrder oOrder=tradeManageService.getOrderByPrimaryKey(orderId);
                //处理买家手机号
                String tmp= PhoneNumUtil.getPhoneNumChange(oOrder.getBuyerUserPhone());
                model.addAttribute("changePhoneNum",tmp);
                //转换对象，将json串类型的order_products的解析成对象
                OrderModel orderModel=Oorder2OrderModel.getOorder2OrderModel(oOrder);
                //填充对象
                model.addAttribute("orderModel",orderModel);
                //查询订单日志
                List<OOrderHistory> orderHistoryList=tradeManageService.getOrderHistoryByOrderId(orderId);
                model.addAttribute("orderHistoryList",orderHistoryList);
                return "/orders/orders_order_infor";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 异步获取物流公司列表
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/order/getAllShippingCompany")
    public String getAllShippingCompany(){
        Subject currentUser= SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()) {
            List<BaseShippingCompany> list=tradeManageService.getAllShippingCompany();
            return JSON.toJSONString(list);
        }
        return "";
    }

    /**
     * 订单发货
     * @param model
     * @param orderId
     * @return
     */
    @RequestMapping(value = "/order/sendGoods",method = RequestMethod.GET)
    public String sendGoods(Model model,@RequestParam("oid") String orderId){
        Subject currentUser= SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()) {
            if (orderId!=null){
                OOrder order=tradeManageService.getOrderByPrimaryKey(orderId);
                model.addAttribute("order",order);
                return "/orders/orders_order_send";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 保存物流信息
     * @return
     */
    @RequestMapping(value = "/order/savingShippingInfor",method = RequestMethod.POST)
    public String savingShippingInfor(Model model,String oid,String code,String name,String num){
        Subject currentUser=SecurityUtils.getSubject();
        if (currentUser.isAuthenticated()){
            OOrder order=new OOrder();
            order.setOrderId(oid);
            order.setShippingCompanyCode(code);
            order.setShippingCompanyName(name);
            order.setShippingTrackingNumber(num);
            order.setOrderStatus(2);
            order.setShippingTime(new Date());
            int status=tradeManageService.updateOOrderByPrimaryKey(order);
            //保存成功
            if (status>0){
                OOrder oOrder=tradeManageService.getOrderByPrimaryKey(oid);
                //添加订单日志信息
                OOrderHistory history=new OOrderHistory();
                history.setHistoryId(UUID.randomUUID().toString());
                history.setComment("卖家已发货");
                history.setoOrderOrderId(oid);
                history.setOrderStatus(2);
                history.setCreateOn(new Date());
                history.setCreateBy(oOrder.getSellerShopName());
                tradeManageService.addOrderHistory(history);

                model.addAttribute("order",oOrder);
                return "/orders/orders_order_send_success";
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 退款订单
     * @return
     */
    @RequestMapping(value = "/order/getAllRefundOrders",method = RequestMethod.GET)
    public String getAllRefundOrders(Model model,@RequestParam(value = "page",defaultValue = "1") int page){
        Subject currentUser= SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()) {
            String userPhoneNum=currentUser.getSession().getAttribute("UserPhoneNum").toString();
            //获取用户信息
            User user=userService.getUserByPhone(userPhoneNum);
            if(user!=null) {
                //查询该卖家用户的对应的商铺id
                WxShop shop = wxShopService.getShopInforByUserId(user.getUserId());
                if (shop != null) {
                    //获取shopId
                    int shopId = shop.getShopId();
                    //获取退款订单列表
                    PageList<OOrderRefund> pageList=tradeManageService.getAllRefundOrdersByShopId(shopId,PAGE_SIZE,page);
                    //转换对象，目的是为了解析orderProducts字段的Json格式的商品列表
                    List<OrderRefundModel> orderRefundModelList= OorderRefund2OrderRefundModel.getOorderRefund2OrderRefundModel(pageList.list);
                    //填充对象
                    model.addAttribute("orderRefundModelList", orderRefundModelList);//产品列表
                    model.addAttribute("pageIndex", pageList.pageIndex);//当前页
                    model.addAttribute("totalPage", pageList.totalPage);//总页数
                    model.addAttribute("totalCount", pageList.totalCount);//总记录数

                    return "/orders/orders_refund_all_orders";
                }
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 退款订单，由订单的状态跳转
     * @param model
     * @param orderStatus
     * @param page
     * @return
     */
    @RequestMapping(value = "/order/getAllRefundOrdersByStatus",method = RequestMethod.GET)
    public String getAllRefundOrdersByStatus(Model model,@RequestParam("status") int orderStatus,
                                             @RequestParam(value = "page",defaultValue = "1") int page){
        Subject currentUser= SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()) {
            String userPhoneNum=currentUser.getSession().getAttribute("UserPhoneNum").toString();
            //获取用户信息
            User user=userService.getUserByPhone(userPhoneNum);
            if(user!=null) {
                //查询该卖家用户的对应的商铺id
                WxShop shop = wxShopService.getShopInforByUserId(user.getUserId());
                if (shop != null) {
                    //获取shopId
                    int shopId = shop.getShopId();
                    //由不同的状态获取退款订单列表
                    PageList<OOrderRefund> pageList=tradeManageService.getAllRefundOrdersByShopIdAndOrderStatus(shopId,orderStatus,PAGE_SIZE,page);
                    //转换对象，为了解析orderProducts里的JSON串
                    List<OrderRefundModel> orderRefundModelList=OorderRefund2OrderRefundModel.getOorderRefund2OrderRefundModel(pageList.list);
                    //填充Model
                    model.addAttribute("orderRefundModelList",orderRefundModelList);//产品列表
                    model.addAttribute("pageIndex", pageList.pageIndex);//当前页
                    model.addAttribute("totalPage", pageList.totalPage);//总页数
                    model.addAttribute("totalCount", pageList.totalCount);//总记录数

                    switch (orderStatus){
                        case -1:return "/orders/orders_refund_close";//已关闭的退款列表
                        case 0:return "/orders/orders_refund_waiting_review";//待审核列表
                        case 1:return "/orders/orders_refund_waiting_goods_return";//等待买家发货
                        case 2:return "/orders/orders_refund_goods_return";//已发货列表
                        case 3:return "/orders/orders_refund_return_success";//成功的订单
                    }
                }
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 退货订单审核
     * @param orderRefundId
     * @return
     */
    @RequestMapping(value = "/order/reviewRefundOrder",method = RequestMethod.GET)
    public String reviewRefundOrder(@RequestParam("oid") String orderRefundId){
        Subject currentUser= SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()) {
            OOrderRefund orderRefund=new OOrderRefund();
            orderRefund.setOrderRefundId(orderRefundId);
            orderRefund.setOrderStatus(1);
            //将退货订单由审核状态转变成等待买家发货
            int status=tradeManageService.updateOOrderRefundByPrimaryKey(orderRefund);

            if (status>0){
                return "redirect:/order/getAllRefundOrdersByStatus/0";
            }else
                return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 退货订单，确认收货
     * @param orderRefundId
     * @return
     */
    @RequestMapping(value = "/order/confirmGetGoods",method = RequestMethod.GET)
    public String confirmGetGoods(@RequestParam("oid") String orderRefundId){
        Subject currentUser= SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()) {
            OOrderRefund orderRefund=new OOrderRefund();
            orderRefund.setOrderRefundId(orderRefundId);
            orderRefund.setOrderStatus(3);
            orderRefund.setGoodsGetTime(new Date());
            //将等待卖家确认收货状态变更成卖家已退款状态
            int status=tradeManageService.updateOOrderRefundByPrimaryKey(orderRefund);

            if (status>0){
                return "redirect:/order/getAllRefundOrdersByStatus?status=2";
            }else
                return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 退货订单详情
     * @param orderRefundId
     * @return
     */
    @RequestMapping(value = "/order/getRefundOrderInfor",method = RequestMethod.GET)
    public String getRefundOrderInfor(Model model,@RequestParam("oid") String orderRefundId){
        Subject currentUser= SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()) {

            if (orderRefundId!=null){
                //获取指定id的退货订单信息
                OOrderRefund orderRefund=tradeManageService.getOorderRefundByPrimaryKey(orderRefundId);
                //将退货订单里的退货商品列表的json格式解析成java对象
                OrderRefundModel orderRefundModel=OorderRefund2OrderRefundModel.getOorderRefund2OrderRefundModel(orderRefund);
                //填充model
                model.addAttribute("orderRefundModel",orderRefundModel);

                if (orderRefund!=null){
                    OOrder order=tradeManageService.getOrderByPrimaryKey(orderRefund.getOrderId());
                    model.addAttribute("order",order);
                    //加密账户
                    String tmp=PhoneNumUtil.getPhoneNumChange(orderRefund.getBuyerUserPhone());
                    model.addAttribute("changPhoneNum",tmp);
                }
                return "/orders/orders_refund_infor";
            }
                return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 同意退款
     * @param addressModel
     * @return
     */
   @RequestMapping(value = "/order/agreeRefundOrder",method = RequestMethod.POST)
    public String agreeRefundOrder(RefundAddressModel addressModel){
       Subject currentUser= SecurityUtils.getSubject();
       if(currentUser.isAuthenticated()) {
           String userPhoneNum=currentUser.getSession().getAttribute("UserPhoneNum").toString();
           //获取用户信息
           User user=userService.getUserByPhone(userPhoneNum);
           if (user!=null){
               OOrderRefund orderRefund=new OOrderRefund();
               orderRefund.setOrderRefundId(addressModel.getOrderRefundId());
               orderRefund.setConsigneeName(user.getUserName());//收货人默认为店铺对应User的username
               orderRefund.setConsigneePhone(user.getUserPhone());//收货人默认为店铺对应User的userPhone
               orderRefund.setProvinceCode(addressModel.getProvinceCode());
               orderRefund.setProvinceName(addressModel.getProvinceName());
               orderRefund.setCityCode(addressModel.getCityCode());
               orderRefund.setCityName(addressModel.getCityName());
               orderRefund.setDistrictCode(addressModel.getDistrictCode());
               orderRefund.setDistrictName(addressModel.getDistrictName());
               orderRefund.setAddress(addressModel.getAddress());
               orderRefund.setOrderStatus(1);
               //同意退货
               tradeManageService.updateOOrderRefundByPrimaryKey(orderRefund);

               return "redirect:/order/getRefundOrderInfor?oid="+addressModel.getOrderRefundId();
           }
           return "redirect:/error";
       }
       return "redirect:/login";
   }


    /**
     * 多条件查询订单
     * @param model
     * @param conditions
     * @return
     */
    @RequestMapping(value = "/order/searchOrderByConditions",method = RequestMethod.POST)
    public String searchOrderByConditions(Model model,String startTime,String endTime,OrderConditionsSelectModel conditions,
                                          @RequestParam(value = "page",defaultValue = "1") int page) {
        Subject currentUser= SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()) {
            String userPhoneNum=currentUser.getSession().getAttribute("UserPhoneNum").toString();
            //获取用户信息
            User user=userService.getUserByPhone(userPhoneNum);
            if(user!=null){
                //查询该卖家用户的对应的商铺id
                WxShop shop=wxShopService.getShopInforByUserId(user.getUserId());
                if (shop!=null){
                    //获取shopId
                    int shopId=shop.getShopId();

                    if(conditions!=null){
                        SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
                        if (startTime!=null&&!startTime.equals(""))
                            try {
                                conditions.setOrderStartTime(sdf.parse(startTime));
                            } catch (ParseException e) {
                                return "redirect:/error";//转换失败，跳转到错误页面
                            }
                        if (endTime!=null&&!endTime.equals(""))
                            try {
                                conditions.setOrderEndTime(sdf.parse(endTime));
                            } catch (ParseException e) {
                                return "redirect:/error";//转换失败，跳转到错误页面
                            }

                        PageList<OOrder> pageList=tradeManageService.getOrderListByConditions(shopId,conditions,PAGE_SIZE,page);

                        //将pageList.list转换成成List<OrderModel>,为了解析orderProduct的json串
                        List<OrderModel> orderModelList=Oorder2OrderModel.getOorder2OrderModel(pageList.list);
                        //Model填充
                        model.addAttribute("orderList", orderModelList);//产品列表
                        model.addAttribute("pageIndex", pageList.pageIndex);//当前页
                        model.addAttribute("totalPage", pageList.totalPage);//总页数
                        model.addAttribute("totalCount", pageList.totalCount);//总记录数

                        return "/orders/orders_all_orders";
                    }
                }
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

    /**
     * 多条件查询退款订单
     * @param model
     * @param conditions
     * @return
     */
    @RequestMapping(value = "/order/searchRefundOrderByConditions",method = RequestMethod.POST)
    public String searchRefundOrderByConditions(Model model,String startTime,String endTime,OrderConditionsSelectModel conditions,
                                                @RequestParam(value = "page",defaultValue = "1") int page){
        Subject currentUser= SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()) {
            String userPhoneNum=currentUser.getSession().getAttribute("UserPhoneNum").toString();
            //获取用户信息
            User user=userService.getUserByPhone(userPhoneNum);
            if(user!=null){
                //查询该卖家用户的对应的商铺id
                WxShop shop=wxShopService.getShopInforByUserId(user.getUserId());
                if (shop!=null){
                    //获取shopId
                    int shopId=shop.getShopId();

                    if(conditions!=null) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
                        if (startTime != null && !startTime.equals(""))
                            try {
                                conditions.setOrderStartTime(sdf.parse(startTime));
                            } catch (ParseException e) {
                                return "redirect:/error";//转换失败，跳转到错误页面
                            }
                        if (endTime != null && !endTime.equals(""))
                            try {
                                conditions.setOrderEndTime(sdf.parse(endTime));
                            } catch (ParseException e) {
                                return "redirect:/error";//转换失败，跳转到错误页面
                            }
                        PageList<OOrderRefund> pageList = tradeManageService.getOrderRefundListByConditions(shopId, conditions, PAGE_SIZE, page);

                        //转换对象，目的是为了解析orderProducts字段的Json格式的商品列表
                        List<OrderRefundModel> orderRefundModelList = OorderRefund2OrderRefundModel.getOorderRefund2OrderRefundModel(pageList.list);
                        //填充对象
                        model.addAttribute("orderRefundModelList", orderRefundModelList);//产品列表
                        model.addAttribute("pageIndex", pageList.pageIndex);//当前页
                        model.addAttribute("totalPage", pageList.totalPage);//总页数
                        model.addAttribute("totalCount", pageList.totalCount);//总记录数

                        return "/orders/orders_refund_all_orders";
                    }
                }
            }
            return "redirect:/error";
        }
        return "redirect:/login";
    }

}